package tool;

import boot.Boot;

public class RamPerfo {
	
	private static RamPerfo instance;
	
	private Runtime rt;
	private Measure[] measures;
	private int index;

	private long freeRamAtStartMeasure;
	
	private RamPerfo() {
		rt = Runtime.getRuntime();
		index = 0;
		measures = new Measure[100];
		
		for (int i = 0; i < measures.length; i++) {
			measures[i] = null;
		}
	}
	
	public static void startMeasure() {
		instance = new RamPerfo();
		instance._defineStartRamMeasure();
	}

	public static void addMeasure(String title) {
		long value = instance.getCurrentMeasure();
		instance._addMeasure(title, value);
	}

	private long getCurrentMeasure() {
		return freeRamAtStartMeasure - rt.freeMemory();
	}

	public static void displayCurrent() {
		instance._displayCurrent();
	}

	private void _displayCurrent() {
		String message = "Available at start: " + getInKo(freeRamAtStartMeasure) + " Ko\n";
		
		for (int i = 0; measures[i] != null; i++) {
			Measure cur = measures[i];
			message += cur.getTitle() + ": " + getInKo(cur.getValue()) + " Ko\n";
		}
		message += "Currently: " + getInKo(getCurrentMeasure()) + " Ko\n";
		Boot.debugErrorAlert(message);
	}

	private long getInKo(long value) {
		return value/1024;
	}

	private void _defineStartRamMeasure() {
		freeRamAtStartMeasure = rt.freeMemory();
	}
	
	private void _addMeasure(String title, long value) {
		measures[index++] = new Measure(title, value);
	}

	private class Measure {
		private long value;
		private String title;
		
		public Measure(String title, long value) {
			super();
			this.value = value;
			this.title = title;
		}

		public long getValue() {
			return value;
		}

		public String getTitle() {
			return title;
		}
	}
}
